'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  // 1. 记录云函数被调用，打印入参和上下文
  console.log('【handleLike】云函数被调用，event：', event);
  console.log('【handleLike】云函数上下文 context：', context);

  // 2. 校验前端传递的参数
  const { postId, userId, receiverId, actionType, postTitle } = event;
  const requiredParams = [
    { key: 'postId', value: postId },
    { key: 'userId', value: userId },
    { key: 'receiverId', value: receiverId },
    { key: 'actionType', value: actionType }
  ];
  const missingParams = requiredParams.filter(item => !item.value);
  if (missingParams.length > 0) {
    console.error('【handleLike】参数缺失，返回失败：', missingParams);
    return { success: false, message: '参数缺失：' + missingParams.map(p => p.key).join(',') };
  }
  console.log('【handleLike】参数校验通过，准备处理');

  try {
    // 3. 处理点赞数据库操作（无论是否自点赞都需要执行）
    console.log('【handleLike】开始处理点赞数据库操作');
    
    // 检查是否已点赞
    const likeRes = await db.collection('user-likes')
      .where({
        user_id: userId,
        post_id: postId
      })
      .get();

    let likeOperationResult = null;
    
    if (likeRes.data.length > 0) {
      // 已点赞，执行取消点赞
      console.log('【handleLike】执行取消点赞操作');
      const likeId = likeRes.data[0]._id;
      await db.collection('user-likes').doc(likeId).remove();
      
      // 更新帖子点赞数
      const postRes = await db.collection('add-content').doc(postId).get();
      if (postRes.data && postRes.data.length > 0) {
        const currentLikes = postRes.data[0].like_count || 0;
        await db.collection('add-content').doc(postId).update({
          like_count: Math.max(0, currentLikes - 1)
        });
        console.log('【handleLike】帖子点赞数更新：', currentLikes, '->', Math.max(0, currentLikes - 1));
      }
      
      likeOperationResult = {
        action: 'unlike',
        isLiked: false,
        message: '取消点赞成功'
      };
      console.log('【handleLike】取消点赞操作完成');
    } else {
      // 未点赞，执行点赞
      console.log('【handleLike】执行点赞操作');
      await db.collection('user-likes').add({
        user_id: userId,
        post_id: postId,
        create_time: Date.now()
      });
      
      // 更新帖子点赞数
      const postRes = await db.collection('add-content').doc(postId).get();
      if (postRes.data && postRes.data.length > 0) {
        const currentLikes = postRes.data[0].like_count || 0;
        await db.collection('add-content').doc(postId).update({
          like_count: currentLikes + 1
        });
        console.log('【handleLike】帖子点赞数更新：', currentLikes, '->', currentLikes + 1);
      }
      
      likeOperationResult = {
        action: 'like',
        isLiked: true,
        message: '点赞成功'
      };
      console.log('【handleLike】点赞操作完成');
    }

    // 4. 处理消息生成（只在点赞且非自点赞时生成）
    let messageResult = null;
    
    if (actionType === 'unlike') {
      console.log('【handleLike】检测到取消点赞，跳过消息生成');
      messageResult = { skipMessage: true, reason: '取消点赞' };
    } else if (userId === receiverId) {
      console.log('【handleLike】检测到自点赞，跳过消息生成');
      messageResult = { skipMessage: true, reason: '自点赞' };
    } else {
      // 调用 createMessageNotification 云函数生成消息
      console.log('【handleLike】开始调用 createMessageNotification 云函数，入参：', {
        postId,
        senderId: userId,
        receiverId,
        actionType: 'like', // 强制设为like，因为只有点赞才生成消息
        postTitle
      });

      const messageRes = await uniCloud.callFunction({
        name: 'createMessageNotification',
        data: {
          postId,
          senderId: userId,
          receiverId,
          actionType: 'like', // 强制设为like
          postTitle
        }
      });

      console.log('【handleLike】createMessageNotification 返回结果：', messageRes);
      
      if (messageRes.result && messageRes.result.success) {
        messageResult = { 
          success: true, 
          message: '消息生成成功',
          data: messageRes.result.data
        };
        console.log('【handleLike】消息生成成功');
      } else {
        messageResult = { 
          success: false, 
          message: '消息生成失败：' + (messageRes.result?.message || '未知错误')
        };
        console.log('【handleLike】消息生成失败：', messageRes.result?.message);
      }
    }

    // 5. 返回综合结果
    console.log('【handleLike】操作完成，返回结果');
    return {
      success: true,
      message: likeOperationResult.message,
      data: {
        likeOperation: likeOperationResult,
        messageOperation: messageResult
      }
    };

  } catch (e) {
    // 6. 捕获异常
    console.error('【handleLike】操作异常（catch）：', e);
    return { success: false, message: '操作失败：' + e.message };
  }
};